package ttk.muxiuesd.screen;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.utils.Scaling;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.viewport.ScalingViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import ttk.muxiuesd.OrthographicCameraController;
import ttk.muxiuesd.util.Log;
import ttk.muxiuesd.world.MainWorld;

/**
 * 游戏主屏幕
 * */
public class MainGameScreen extends ScreenAdapter {
    public static String TAG = MainGameScreen.class.getName();

    public Batch batch = new SpriteBatch();
    public Viewport viewport;
    public OrthographicCameraController cameraController;
    public ShapeRenderer shapeRenderer = new ShapeRenderer() {{
        setAutoShapeType(true);
    }};

    private MainWorld world;


    @Override
    public void show() {
        int w = Gdx.graphics.getWidth();
        int h = Gdx.graphics.getHeight();
        this.cameraController = new OrthographicCameraController(new OrthographicCamera());
        this.viewport = new ScalingViewport(Scaling.fit, w, h, cameraController.camera);

        this.initWorld();

        Log.print(TAG, "初始化完成！");
    }


    @Override
    public void render(float delta) {
        if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
            Log.print(TAG, "游戏退出！");
            Gdx.app.exit();
        }

        // 清屏
        //ScreenUtils.clear(new Color(0.2f, 0.5f, 0.6f, 1f));
        ScreenUtils.clear(Color.BLACK);

        //更新
        this.world.update(delta);

        Camera camera = viewport.getCamera();
        camera.update();
        Batch batch = this.batch;
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        //绘制
        this.world.draw(batch);
        batch.end();

        shapeRenderer.begin();
        shapeRenderer.setProjectionMatrix(camera.combined);
        this.world.render(shapeRenderer);
        shapeRenderer.end();
    }

    @Override
    public void resize(int width, int height) {
        //Log.print(TAG, "调整窗口大小为：" + width + ", " + height);
        viewport.setWorldSize(width, height);
        cameraController.resize(width, height);
    }

    @Override
    public void hide() {
        super.hide();
    }

    @Override
    public void pause() {
        super.pause();
    }

    @Override
    public void resume() {
        super.resume();
    }

    @Override
    public void dispose() {
        this.world.dispose();
    }

    private void initWorld () {
        this.world = new MainWorld(this);
    }
}
